﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Elasticsearch.Synchronize.Domain.Aggregates.SynchronizeAggregate;
using Elasticsearch.Synchronize.Domain.Interface;
using Elasticsearch.Synchronize.DomainEventHandler.Interface;
using HYService.BLModels.Event;
using MongoDB.Driver;
using Nest;

namespace Elasticsearch.Synchronize.DomainEventHandler.Processor
{
    public abstract class BaseProcessor<TModel> : IProcessor<TModel> where TModel : class
    {
        protected readonly SynchronizeItem _synchronizeItem;

        protected readonly IMongoCollection<TModel> _mongoCollection;

        protected readonly ElasticClient _elasticClient;

        protected readonly ISynchronizeItemRepository _repository;

        protected BaseProcessor(SynchronizeItem synchronizeItem, ISynchronizeItemRepository repository)
        {
            _synchronizeItem = synchronizeItem;

            var mongoClient = new MongoClient(_synchronizeItem.MongoSeverUrl);
            var mongoDatabase = mongoClient.GetDatabase(_synchronizeItem.MongoDatabase);
            _mongoCollection = mongoDatabase.GetCollection<TModel>(_synchronizeItem.MongoCollection);

            var settings = new ConnectionSettings(new Uri(_synchronizeItem.ElasticsearchServerUrl));
            settings.DisableDirectStreaming();
            settings.DefaultFieldNameInferrer(f => f);
            _elasticClient = new ElasticClient(settings);

            _repository = repository;
        }

        public abstract List<TModel> Query();

        public abstract void Pour();

        public void Start()
        {
            this.Pour();
        }
    }
}